package com.zone.sdk.common.http.base;

import com.zone.sdk.common.http.ObservableService;
import com.zone.sdk.common.http.OkHttpManager;
import com.zone.sdk.common.http.callback.ResultCallBack;

import org.jetbrains.annotations.NotNull;

import io.reactivex.Observable;
import io.reactivex.observers.DisposableObserver;

/**
 * @Author: pkqlqx
 * @CreateDate: 2021/12/4 10:54
 * @Description:
 */
public abstract class BaseCloudServiceManager {

    protected ObservableService observableService;

    protected OkHttpManager okHttpManager;

    public BaseCloudServiceManager() {
        okHttpManager = OkHttpManager.getInstance();
        observableService = ObservableService.getInstance();
    }

    public void init(String baseUrl){
        okHttpManager.init(baseUrl);
    }

//    public <T> T build(final Class<T> service){
//        return okHttpManager.build(service);
//    }

    /*********************************************************************************/


    protected void innerExecute(Observable observable, ResultCallBack<Result> callback){
        observableService.execute(observable, new DisposableObserver<Result>(){

            @Override
            public void onNext(@NotNull Result o) {
                if (callback != null) {
                    callback.onSuccess(o);
                }
                if (!isDisposed()) {
                    dispose();
                }
            }

            @Override
            public void onError(@NotNull Throwable e) {
                if (e == null) {
                    e = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
                }
                if (callback != null) {
                    callback.onError("", e.getMessage());
                }
                if (!isDisposed()) {
                    dispose();
                }
            }

            @Override
            public void onComplete() {
                if (!isDisposed()) {
                    try {
                        callback.onComplete();
                    } finally {
                        dispose();
                    }
                }
            }
        });
    }

}
